<template>
  <div class="message-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">聊天信息管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleExportSessionMessages" :disabled="!selectedSessionId">
          导出会话消息
        </el-button>
        <el-button type="danger" @click="handleDeleteSelectedMessages" :disabled="selectedMessages.length === 0">
          删除选中消息
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-select v-model="selectedSessionId" placeholder="选择会话" class="filter-select session-filter">
        <el-option label="全部会话" value="" />
        <el-option v-for="session in sessions" :key="session.id" :label="session.label" :value="session.id" />
      </el-select>
      <el-input 
        v-model="searchKeyword" 
        placeholder="搜索消息内容/发送者" 
        prefix-icon="Search"
        class="search-input"
        @keyup.enter="handleSearch"
      />
      <el-select v-model="messageTypeFilter" placeholder="消息类型" class="filter-select">
        <el-option label="全部" value="" />
        <el-option label="文本" value="text" />
        <el-option label="图片" value="image" />
        <el-option label="文件" value="file" />
        <el-option label="语音" value="voice" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="date-picker"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
    </div>

    <!-- 消息表格 -->
    <el-table 
      v-loading="loading" 
      :data="messagesData" 
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="消息ID" width="180" sortable />
      <el-table-column prop="sender" label="发送者" width="150" sortable>
        <template #default="scope">
          <div class="sender-info">
            <el-avatar :src="scope.row.sender.avatar" class="sender-avatar" />
            <span>{{ scope.row.sender.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sessionId" label="所属会话" width="180" sortable />
      <el-table-column prop="type" label="消息类型" width="100" sortable>
        <template #default="scope">
          <el-tag :type="getMessageTypeTagType(scope.row.type)">
            {{ getMessageTypeLabel(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="消息内容" min-width="300">
        <template #default="scope">
          <div class="message-content" :title="scope.row.content">
            <div v-if="scope.row.type === 'image'" class="image-preview">
              <el-image 
                :src="scope.row.content" 
                :preview-src-list="[scope.row.content]"
                preview-teleported="true"
                style="width: 100px; height: 100px"
              >
                <template #placeholder>
                  <div class="image-placeholder">图片</div>
                </template>
              </el-image>
            </div>
            <div v-else-if="scope.row.type === 'file'" class="file-preview">
              <el-icon><Document /></el-icon>
              <a href="javascript:void(0)" @click="handleDownloadFile(scope.row)">{{ getFileName(scope.row.content) }}</a>
            </div>
            <div v-else-if="scope.row.type === 'voice'" class="voice-preview">
              <el-icon><Service /></el-icon>
              <span>{{ scope.row.content }}</span>
            </div>
            <div v-else>{{ scope.row.content }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sendTime" label="发送时间" sortable>
        <template #default="scope">
          {{ formatTime(scope.row.sendTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-button type="danger" link @click="handleDeleteMessage(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalMessages"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Document, Service } from '@element-plus/icons-vue'
import { downloadJsonFile, generateFileNameWithDateRange } from '../utils/downloadUtils.js'
import { exportSessionMessages } from '../utils/apiService.js'

// 表格数据
const messages = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalMessages = ref(0)
const selectedMessages = ref([])

// 搜索和筛选条件
const searchKeyword = ref('')
const messageTypeFilter = ref('')
const dateRange = ref([])
const selectedSessionId = ref('')
const sessions = ref([])

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取消息类型标签
const getMessageTypeTagType = (type) => {
  const typeMap = {
    'text': 'primary',
    'image': 'success',
    'file': 'warning',
    'voice': 'info'
  }
  return typeMap[type] || 'default'
}

// 获取消息类型标签
const getMessageTypeLabel = (type) => {
  const typeMap = {
    'text': '文本',
    'image': '图片',
    'file': '文件',
    'voice': '语音'
  }
  return typeMap[type] || '未知'
}

// 获取文件名
const getFileName = (filePath) => {
  if (!filePath) return '文件'
  const parts = filePath.split('/')
  return parts[parts.length - 1]
}

// 过滤后的消息数据
const messagesData = computed(() => {
  let filtered = [...messages.value]
  
  // 会话过滤
  if (selectedSessionId.value) {
    filtered = filtered.filter(message => message.sessionId === selectedSessionId.value)
  }
  
  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(message => 
      message.content.toLowerCase().includes(keyword) ||
      message.sender.username.toLowerCase().includes(keyword) ||
      message.sessionId.toLowerCase().includes(keyword)
    )
  }
  
  // 消息类型过滤
  if (messageTypeFilter.value) {
    filtered = filtered.filter(message => message.type === messageTypeFilter.value)
  }
  
  // 日期范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0])
    const endDate = new Date(dateRange.value[1])
    endDate.setHours(23, 59, 59, 999) // 设置为当天结束时间
    
    filtered = filtered.filter(message => {
      const messageDate = new Date(message.sendTime)
      return messageDate >= startDate && messageDate <= endDate
    })
  }
  
  // 更新总数
  totalMessages.value = filtered.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 模拟加载消息数据
const loadMessagesData = () => {
  loading.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 生成一些模拟用户数据
    const mockUsers = Array.from({ length: 10 }, (_, i) => ({
      id: `user${i + 1}`,
      username: `user${i + 1}`,
      avatar: `https://api.dicebear.com/9.x/avataaars/svg?seed=user${i + 1}`
    }))
    
    // 生成一些模拟消息数据
    const messageTypes = ['text', 'image', 'file', 'voice']
    const textMessages = [
      '你好！很高兴认识你',
      '这个项目进展怎么样了？',
      '我们明天上午10点开会讨论一下',
      '请查看附件中的文档',
      '收到请回复',
      '好的，我明白了',
      '谢谢大家的配合',
      '周末愉快！'
    ]
    
    const mockMessages = Array.from({ length: 50 }, (_, i) => {
      const type = messageTypes[Math.floor(Math.random() * messageTypes.length)]
      let content = ''
      
      switch (type) {
        case 'text':
          content = textMessages[Math.floor(Math.random() * textMessages.length)]
          break
        case 'image':
          content = `https://picsum.photos/200/200?random=${i}`
          break
        case 'file':
          content = `/uploads/files/document_${i + 1}.pdf`
          break
        case 'voice':
          content = `[语音消息 00:${Math.floor(Math.random() * 50) + 10}]`
          break
      }
      
      const sender = mockUsers[Math.floor(Math.random() * mockUsers.length)]
      const sessionId = `session_${Math.floor(Math.random() * 10) + 1000}`
      const sendTime = new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
      
      return {
        id: `msg_${Date.now() + i}`,
        sender: sender,
        sessionId: sessionId,
        type: type,
        content: content,
        sendTime: sendTime
      }
    })
    
    // 按发送时间排序
    mockMessages.sort((a, b) => new Date(b.sendTime) - new Date(a.sendTime))
    
    messages.value = mockMessages
    
    // 提取所有会话ID并生成会话列表
    const sessionMap = new Map()
    mockMessages.forEach(msg => {
      if (!sessionMap.has(msg.sessionId)) {
        sessionMap.set(msg.sessionId, { id: msg.sessionId, label: `${msg.sessionId}` })
      }
    })
    sessions.value = Array.from(sessionMap.values())
    
    loading.value = false
  }, 500)
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = ''
  messageTypeFilter.value = ''
  dateRange.value = []
  selectedSessionId.value = ''
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 选择消息变化
const handleSelectionChange = (selection) => {
  selectedMessages.value = selection
}

// 下载文件
const handleDownloadFile = (message) => {
  ElMessage.info(`模拟下载文件: ${getFileName(message.content)}`)
}

// 删除单个消息
const handleDeleteMessage = (messageId) => {
  ElMessageBox.confirm(
    '确定要删除这条消息吗？此操作不可撤销。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      loading.value = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        const index = messages.value.findIndex(msg => msg.id === messageId)
        if (index !== -1) {
          messages.value.splice(index, 1)
        }
        ElMessage.success('消息已删除')
        loading.value = false
      }, 300)
    })
    .catch(() => {
      ElMessage.info('已取消删除操作')
    })
}

// 删除选中的消息
const handleDeleteSelectedMessages = () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请先选择要删除的消息')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedMessages.value.length} 条消息吗？此操作不可撤销。`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      loading.value = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        const selectedIds = selectedMessages.value.map(msg => msg.id)
        messages.value = messages.value.filter(msg => !selectedIds.includes(msg.id))
        selectedMessages.value = []
        ElMessage.success(`已成功删除 ${selectedIds.length} 条消息`)
        loading.value = false
      }, 300)
    })
    .catch(() => {
      ElMessage.info('已取消批量删除操作')
    })
}

// 处理导出会话消息
const handleExportSessionMessages = async () => {
  if (!selectedSessionId.value) {
    ElMessage.warning('请先选择一个会话')
    return
  }
  
  loading.value = true
  
  try {
    // 从后端获取指定会话和时间范围内的消息
    const response = await exportSessionMessages(
      selectedSessionId.value,
      dateRange.value && dateRange.value.length === 2 ? dateRange.value[0] : null,
      dateRange.value && dateRange.value.length === 2 ? dateRange.value[1] : null
    )
    
    // 从响应中获取消息数据
    const exportMessages = response && response.data ? response.data : []
    
    // 格式化导出数据
    const exportData = exportMessages.map(msg => ({
      '消息ID': msg.id,
      '发送者': msg.sender ? msg.sender.username : '未知',
      '会话ID': msg.sessionId,
      '消息类型': getMessageTypeLabel(msg.type),
      '消息内容': msg.content,
      '发送时间': formatTime(msg.sendTime)
    }))
    
    // 使用公共下载工具函数实现导出功能 todo 后续需要获取后端的数据（根据会话id以及会话的时间范围拿到数据作为exportData）
    const fileName = generateFileNameWithDateRange(
      selectedSessionId.value,
      dateRange.value,
      '.json'
    )
    
    // 确保导出的是格式化后的数据
    await downloadJsonFile(exportData, fileName, 800)
    
    ElMessage.success(`已成功导出 ${exportMessages.length} 条消息到 ${fileName}`)
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出文件失败，请重试')
  } finally {
    loading.value = false
  }
}

// 页面加载时初始化数据
onMounted(() => {
  loadMessagesData()
})
</script>

<style scoped>
.message-management {
  width: 100%;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 搜索和筛选区域 */
.search-filter-section {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 120px;
}

.session-filter {
  width: 180px;
}

.date-picker {
  width: 250px;
}

/* 发送者信息样式 */
.sender-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sender-avatar {
  width: 28px;
  height: 28px;
}

/* 消息内容样式 */
.message-content {
  line-height: 1.5;
}

/* 图片预览样式 */
.image-preview {
  padding: 8px 0;
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 12px;
  border-radius: 4px;
}

/* 文件预览样式 */
.file-preview {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #409eff;
  padding: 8px 0;
}

.file-preview a {
  color: #409eff;
  text-decoration: none;
}

.file-preview a:hover {
  text-decoration: underline;
}

/* 语音预览样式 */
.voice-preview {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  padding: 8px 0;
}

/* 分页区域 */
.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-input {
    width: 250px;
  }
  
  .date-picker {
    width: 220px;
  }
}

@media (max-width: 1024px) {
  .search-input {
    width: 200px;
  }
  
  .filter-select {
    width: 100px;
  }
  
  .date-picker {
    width: 200px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .search-filter-section {
    flex-direction: column;
  }
  
  .search-input,
  .filter-select,
  .date-picker {
    width: 100%;
  }
}
</style>